package com.xiaoyu.lanling.feature.view

import android.content.Context
import android.util.AttributeSet
import android.view.SoundEffectConstants
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.xiaoyu.lanling.R
import kotlinx.android.synthetic.main.view_main_bottom_image_button.view.*

class MainBottomAnimButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    companion object {
        private const val DEFAULT_UNCHECKED_TEXT_COLOR = R.color.cpColorTertiaryText
        private const val DEFAULT_CHECKED_TEXT_COLOR = R.color.cpColorPrimaryText
    }

    private var mOnCheckedChangeListener: OnCheckedChangeListener? = null

    private var mUncheckedTextColor = 0
    private var mCheckedTextColor = 0

    init {
        init(context, attrs, defStyleAttr)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        View.inflate(context, R.layout.view_main_bottom_image_button, this)

        mCheckedTextColor = resources.getColor(DEFAULT_CHECKED_TEXT_COLOR)
        mUncheckedTextColor = resources.getColor(DEFAULT_UNCHECKED_TEXT_COLOR)

        val typedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.MainBottomImageButton,
            defStyleAttr,
            0
        )
        typedArray.getDrawable(R.styleable.MainBottomImageButton_src)?.let {
            item_main_bottom_image.setImageDrawable(it)
        }
        val text = typedArray.getString(R.styleable.MainBottomImageButton_text)

        isClickable = true
        item_main_bottom_text.text = text
        typedArray.recycle()
    }

    override fun performClick(): Boolean {
        if (isSelected) {
            return true
        }
        toggle()
        val handled = super.performClick()
        if (!handled) {
            // View only makes a sound effect if the onClickListener was
            // called, so we'll need to make one here instead.
            playSoundEffect(SoundEffectConstants.CLICK)
        }
        return handled
    }

    private fun toggle() {
        isSelected = !isSelected
    }

    override fun dispatchSetSelected(selected: Boolean) {
        super.dispatchSetSelected(selected)
        playSoundEffect(SoundEffectConstants.CLICK)
        mOnCheckedChangeListener?.onCheckedChanged(this, selected)
        refreshView(selected)
    }

    private fun refreshView(checked: Boolean) {
        item_main_bottom_text.setTextColor(if (checked) mCheckedTextColor else mUncheckedTextColor)
    }

    fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
        mOnCheckedChangeListener = listener
    }

    interface OnCheckedChangeListener {
        fun onCheckedChanged(
            buttonView: MainBottomAnimButton,
            isSelected: Boolean
        )
    }
}